import os
import fnmatch
import logging

import settings
import uploader


log = logging.getLogger(settings.log_name_applog)


def __get_filepaths():
    directory = settings.download_save_path
    filepaths = os.listdir(directory)
    json_paths = sorted([directory + path for path in filepaths if path.endswith('.json')])
    video_paths = sorted([directory + path for path in filepaths if path.endswith('.mp4') or path.endswith('.flv')])
    length_jsons = len(json_paths)
    length_videos = len(video_paths)

    if length_jsons is length_videos:
        result = [json_paths, video_paths, length_jsons]

    else:
        result = None

    return result


def __token_validation():
    token = settings.tudou_api_access_token
    # TODO


def do_upload():
    paths = __get_filepaths()
    output = ''

    if paths is None:
        print 'cannot start uploading process, please check the json files'
        log.warning('upload process abandoned due to: json and video name do not match.')
    else:
        for index in range(0, paths[-1]):
                result, status = uploader.upload_video(paths[0][index], paths[1][index])
                if status is settings.tudou_api_upload_status_finish:
                    output += result
                else:
                    print 'upload failed: %s' % paths[1][index]

    return output